//
//  DetailTable.m
//  SplitForce
//
//  Created by Ron Hess on 7/8/10.
//  Copyright 2010 Salesforce.com. All rights reserved.
//

#import "DetailTable.h"
#import "UITableViewCellFixed.h"

@implementation DetailTable 

// really we are only drawing the detail of the page layout at this time, 
// not the edit, not the related lists those are seperate tables

@synthesize theLayout, detailLayouSections,detailItem,describe;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
	
	SplitForceAppDelegate *app = (SplitForceAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	// this hits a cache we pre loaded in rootviewcontroller
	NSArray *layouts = [[app.rootViewController.client describeLayout:@"account"] layouts];
	
	theLayout = [layouts objectAtIndex:0];	// this is just the first layout, not a particular layout 
	// TODO fetch a layout by a name?
	
	detailLayouSections = [[theLayout detailLayoutSections] copyWithZone:nil]; // cache this
	
	describe = [[app.rootViewController.client describeSObject:@"Account"] retain];
	
	return self;
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	
	// why does setting the frame make the table view scroll properly ?
	CGRect r = self.tableView.frame;
	self.tableView.frame = CGRectMake(0,0,r.size.height,r.size.width);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {	
	return [detailLayouSections count] ;
}

// Return the number of rows in the section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [[[detailLayouSections objectAtIndex:section] layoutRows] count];	
	
}

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section {
	return [[detailLayouSections objectAtIndex:section] heading];
}

- (NSString *) fieldValueFormattedFromItem : (ZKDescribeLayoutItem *)item {
	NSString *val = @"";
	if ([[item layoutComponents] count] > 0) {
		
		ZKDescribeLayoutComponent *laycomp = [[item layoutComponents] objectAtIndex:0];
		
		NSString *fieldName = [laycomp value];
		ZKDescribeField *field = [describe fieldWithName:fieldName];
		
		// set a formatted value
		val = [detailItem fieldValueFormatted:fieldName :field]; 
	}
	return val!=nil?val:@"" ;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
//	NSLog(@"section %d row %d",indexPath.section,indexPath.row);

    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell %d %d",indexPath.section,indexPath.row];
    
    UITableViewCell *cell;
	cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCellFixed alloc] initWithStyle:UITableViewCellStyleValue2 
											reuseIdentifier:CellIdentifier] autorelease];		
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
	
    // Configure the cell...
	//
		
	ZKDescribeLayoutRow *dlr = [[[detailLayouSections objectAtIndex:indexPath.section] layoutRows] objectAtIndex:indexPath.row];
	@try {
		
		ZKDescribeLayoutItem *item = [[dlr layoutItems] objectAtIndex:0]; // first column
		
		cell.textLabel.text = [item placeholder] ? @" ": [NSString stringWithFormat:@"%@", [item label]];
		
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",[self fieldValueFormattedFromItem:item] ];

	} @catch (NSException * e) {
		
	}
	
	
	@try {
		ZKDescribeLayoutItem *item2 = [[dlr layoutItems] objectAtIndex:1];

		[(UITableViewCellFixed *)cell textLabel2].text = [NSString stringWithFormat:@"%@", [item2 label]];
	
		[(UITableViewCellFixed *)cell detailTextLabel2].text = [NSString stringWithFormat:@"%@",[self fieldValueFormattedFromItem:item2] ];

		[(UITableViewCellFixed *)cell setHasTwoCols:YES];
	}
	@catch (NSException * e) {
		// single column ends here
	}
	
//	cell.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;

	return cell;
}



- (void)setDetailItem:(id)newDetailItem {
    if (detailItem != newDetailItem) {
        [detailItem release];
        detailItem = [newDetailItem retain];
		[super.tableView reloadData];
    }
	
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	NSLog(@"did selectrow at index");
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[detailLayouSections dealloc];
}

@end

